import { getCart, getUser, addCart, updateCart, delCart, order } from '../../assets/js/request.js';
const state = {
    cartProducts: JSON.parse(sessionStorage.getItem('cartProducts')) || [],
    userId: sessionStorage.getItem('userId') || '',
}
const mutations = {
    //获取登录userId
    getUserId(state, id) {
        state.userId = id;
        sessionStorage.setItem('userId', id)
    },
    setCartprod(state, prod) {
        state.cartProducts = prod;
    },
    //添加购物车
    addToCart(state, product) {
        //商品不存在
        state.cartProducts.unshift({
            ...product,
            isChecked: true,
            totalPrice: product.price,
        })
    },
    //商品加1
    Increment(state, product) {
        product.num++;
        product.totalPrice = product.num * product.s_good.sale_price
    },
    //商品减1
    Decrement(state, product) {
        product.num--;
        product.totalPrice = product.num * product.s_good.sale_price
    },
    delProduct({ cartProducts }, prod) {
        cartProducts.splice(cartProducts.indexOf(prod), 1);
    },

}


const actions = {
    async getCartprod({ commit }) {
        let res = await getCart();
        let arr = [];
        res.forEach(ele => {
            if (ele.user_id == state.userId) {
                arr.push({ ...ele, isChecked: true, totalPrice: ele.num * ele.s_good.sale_price })
            }
        });
        sessionStorage.setItem('cartProducts', JSON.stringify(arr));
        commit('setCartprod', arr)
    },
    //添加购物车
    addtocart(state, product) {
        let flag = false;
        let indexNew = 0;
        state.state.cartProducts.forEach((ele, index) => {
            if (ele.goods_id == product.id) {
                flag = true;
                indexNew = index
            }
        })
        if (flag) {
            console.log(state.state.cartProducts[indexNew].id);
            updateCart(state.state.cartProducts[indexNew].id, { num: state.state.cartProducts[indexNew].num + 1 })
            state.commit('Increment', state.state.cartProducts[indexNew])
        } else {
            addCart({
                goods_id: product.id,
                num: 1,
                project_id: 13
            }).then(() => {
                state.dispatch('getCartprod');
            })
        }
    },
    //商品加1
    increment(state, product) {
        updateCart(product.id, { num: product.num + 1 });
        state.commit('Increment', product);
    },
    //商品减1
    decrement(state, product) {
        updateCart(product.id, { num: product.num - 1 });
        state.commit('Decrement', product);
    },
    //删除商品
    delone(state, item) {
        delCart(item.id).then(() => {
            state.commit('delProduct', item);
        })
    },
    //清空购物车
    clearCartOut(state) {
        state.state.cartProducts.forEach((ele, index) => {
            if (ele.isChecked == true) {
                delCart(ele.id);
                state.state.cartProducts.splice(index, 1);
            }
        })
        sessionStorage.setItem('cartProducts', JSON.stringify(state.state.cartProducts))
    },
}

const getters = {
    totalCount(state) {
        return state.cartProducts.reduce((sum, prod) => sum + prod.count, 0)
    },
    totalPrice(state) {
        return state.cartProducts.reduce((sum, prod) => sum + prod.totalPrice, 0)
    },
    selectCount(state) {
        let sum = 0;
        state.cartProducts.forEach(ele => {
            if (ele.isChecked) {
                sum += ele.count;
            }
        });
        return sum;

    },
    selectPrice(state) {
        // localStorage.setItem('cartProducts', JSON.stringify(state.cartProducts));
        let sum = 0;
        state.cartProducts.forEach(ele => {
            if (ele.isChecked) {
                sum += ele.totalPrice;
            }
        });
        return sum;
    },
}


export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
}